package com.chy.common;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chy.entity.User;
import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通用返回结果，服务端响应的数据最终都会封装成此对象
 * @param <T>
 */
@Data
public class R<T> implements Serializable {

    public Integer code; //编码：1成功，0和其它数字为失败

    public String msg; //错误信息

    public T data; //数据

    public Map map = new HashMap(); //动态数据
    private List<T> list;

    private Long total;

    public static <T> R<T> success(T object, String msg) {
        R<T> r = new R<T>();
        r.data = object;
        r.msg = msg;
        r.code = 1;
        r.list = new ArrayList<T>();
        r.total = 0L;
        return r;
    }

    public static <T> R<T> success(Page pageInfo, String msg) {
        R<T> res = new R<T>();
        res.list = pageInfo.getRecords();
        res.msg = msg ;
        res.code = 1;
        res.total = pageInfo.getTotal();
        return res;
    }

    public static R<Page> success(Page pageInfo) {
        R<Page> res = new R<>();
        res.list = pageInfo.getRecords();
        res.msg = "请求成功";
        res.code = 1;
        res.total = pageInfo.getTotal();
        System.out.println(res);
        return res;
    }

    public static <T> R<T> success(T object) {
        R<T> r = new R<T>();
        r.data = object;
        r.msg = "请求成功";
        r.code = 1;
        r.list = new ArrayList<T>();
        r.total = 0L;
        return r;
    }

    public static <T> R<T> success(String msg) {
        R<T> r = new R<T>();
        r.msg = msg;
        r.code = 1;
        r.list = new ArrayList<T>();
        r.total = 0L;
        return r;
    }

    public static R success() {
        R r = new R();
        r.msg = "请求成功";
        r.code = 1;
        r.list = new ArrayList<>();
        r.total = 0L;
        return r;
    }
    public static <T> R<T> error(String msg) {
        R r = new R();
        r.msg = msg;
        r.code = 0;
        r.list = new ArrayList<T>();
        r.total = 0L;
        return r;
    }

    public static <T> R<T> error() {
        R r = new R();
        r.msg = "请求失败";
        r.code = 0;
        r.list = new ArrayList<T>();
        r.total = 0L;
        return r;
    }
    public static <T> R<T> noLogin() {
        R r = new R();
        r.msg = "用户未登录！";
        r.code = 5001;
        r.list = new ArrayList<T>();
        r.total = 0L;
        return r;
    }

    public static <T> R<T> loginExpire() {
        R r = new R();
        r.msg = "登录已过期！";
        r.code = 5002;
        r.list = new ArrayList<T>();
        r.total = 0L;
        return r;
    }

    public R<T> add(String key, Object value) {
        this.map.put(key, value);
        return this;
    }

}
